<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="停机编号" prop="recordCode">
        <el-input v-model="queryParams.recordCode" placeholder="请输入停机记录编号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="停机类型" prop="shutdownType">
        <el-select v-model="queryParams.shutdownType" placeholder="请选择停机类型">
          <el-option v-for="dict in dict.type.mes_shutdown_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="设备ID" prop="machineryId">
        <el-input
          v-model="queryParams.machineryId"
          placeholder="请输入设备ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="设备编号" prop="machineryCode">
        <el-input v-model="queryParams.machineryCode" placeholder="请输入设备编号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="设备名称" prop="machineryName">
        <el-input v-model="queryParams.machineryName" placeholder="请输入设备名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="是否正常停机" prop="isNormally">
        <el-input v-model="queryParams.isNormally" placeholder="请输入是否正常停机" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="停机时间" prop="shutdownTime">
        <!-- <el-date-picker clearable v-model="queryParams.shutdownTime" type="date" value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择停机时间">
        </el-date-picker> -->
        <el-date-picker
              v-model="queryParams.shutdownTime"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd">
            </el-date-picker>
      </el-form-item>
      <el-form-item label="复机时间" prop="resumptionTime">
        <!-- <el-date-picker clearable v-model="queryParams.resumptionTime" type="date" value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择复机时间"> -->
          <el-date-picker
                v-model="queryParams.resumptionTime"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                value-format="yyyy-MM-dd">
              </el-date-picker>
        </el-date-picker>
      </el-form-item>
      <el-form-item label="影响时长" prop="affectDuration">
        <!-- <el-input-number v-model="queryParams.affectDuration" size="medium" :precision="2" :step="10" :max="99999999"
          @keyup.enter.native="handleQuery"></el-input-number> -->
        <el-input v-model="queryParams.affectDuration" placeholder="请输入影响时长" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="工单ID" prop="workorderId">
        <el-input
          v-model="queryParams.workorderId"
          placeholder="请输入工单ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="任务编号" prop="workorderCode">
        <el-input v-model="queryParams.workorderCode" placeholder="请输入任务编号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="任务名称" prop="workorderName">
        <el-input v-model="queryParams.workorderName" placeholder="请输入任务名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="操作人" prop="operator">
        <el-input v-model="queryParams.operator" placeholder="请输入操作人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="预留字段1" prop="attr1">
        <el-input
          v-model="queryParams.attr1"
          placeholder="请输入预留字段1"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预留字段2" prop="attr2">
        <el-input
          v-model="queryParams.attr2"
          placeholder="请输入预留字段2"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['mes:dv:shutdown:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['mes:dv:shutdown:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mes:dv:shutdown:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['mes:dv:shutdown:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shutdownList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="停机记录ID" align="center" prop="recordId" />
      <el-table-column label="停机编号" width="120" align="center" prop="recordCode" />
      <el-table-column label="停机类型" align="center" prop="shutdownType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_shutdown_type" :value="scope.row.shutdownType" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="设备ID" align="center" prop="machineryId" /> -->
      <el-table-column label="设备编号" align="center" prop="machineryCode" />
      <el-table-column label="设备名称" align="center" prop="machineryName" />
      <el-table-column label="停机原因" :show-overflow-tooltip="true" align="center" prop="shutdownContent" />
      <el-table-column label="是否正常停机" width="100px" align="center" prop="isNormally">
        <template slot-scope="scope">
          {{scope.row.isNormally == 1 ? "是" : "否"}}
        </template>
      </el-table-column>
      <el-table-column label="停机时间" align="center" prop="shutdownTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.shutdownTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="复机时间" align="center" prop="resumptionTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.resumptionTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="影响时长" align="center" prop="affectDuration" />
      <!-- <el-table-column label="工单ID" align="center" prop="workorderId" /> -->
      <el-table-column label="任务编号" width="150" align="center" prop="workorderCode" />
      <el-table-column label="任务名称" align="center" prop="workorderName" />
      <el-table-column label="操作人" align="center" prop="operator" />
      <el-table-column label="备注" align="center" prop="remark" />
      <!-- <el-table-column label="预留字段1" align="center" prop="attr1" /> -->
      <!-- <el-table-column label="预留字段2" align="center" prop="attr2" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:dv:shutdown:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['mes:dv:shutdown:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改设备停复机记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="停机编号" prop="recordCode">
          <el-input v-model="form.recordCode" placeholder="请输入停机记录编号" />
        </el-form-item>
        <el-form-item label="停机类型" prop="shutdownType">
          <el-select v-model="form.shutdownType" placeholder="请选择停机类型">
            <el-option v-for="dict in dict.type.mes_shutdown_type" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="设备ID" prop="machineryId">
          <el-input v-model="form.machineryId" placeholder="请输入设备ID" />
        </el-form-item> -->
        <el-form-item label="设备编号" prop="machineryCode">
          <el-input v-model="form.machineryCode" style="width: 200px;" placeholder="请输入设备编号" readonly="readonly">
            <el-button slot="append" style="width: 30px; padding: 10px;" @click="handleMachineryAdd"
              icon="el-icon-search"></el-button>
          </el-input>
          <MachinerySelectSingle ref="machinerySelect" @onSelected="onMachineryAdd"></MachinerySelectSingle>
        </el-form-item>
        <el-form-item label="设备名称" prop="machineryName">
          <el-input v-model="form.machineryName" disabled placeholder="选择设备后自动填充" />
        </el-form-item>

        <el-form-item label="停机时间" prop="shutdownTime">
          <el-date-picker clearable v-model="form.shutdownTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择停机时间" @change="calculateEndTime">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="复机时间" prop="resumptionTime">
          <el-date-picker clearable v-model="form.resumptionTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择复机时间" disabled>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="影响时长(分钟)" prop="affectDuration">
          <el-input-number v-model="form.affectDuration" :precision="0" :step="10" :max="99999999" @change="calculateEndTime"></el-input-number>
          <!-- <el-input v-model="form.affectDuration" placeholder="请输入影响时长" /> -->
        </el-form-item>
        <!-- <el-form-item label="工单ID" prop="workorderId">
          <el-input v-model="form.workorderId" placeholder="请输入工单ID" />
        </el-form-item> -->
        <el-form-item label="任务编号" prop="workorderCode">
          <el-input v-model="form.workorderCode" style="width: 200px;" placeholder="请输入任务编号">
            <el-button slot="append" style="width: 30px; padding: 10px;" icon="el-icon-search"
              @click="handleWorkorderSelect"></el-button>
          </el-input>
          <WorkorderSelect ref="woSelect" @onSelected="onWorkorderSelected"></WorkorderSelect>
        </el-form-item>
        <el-form-item label="任务名称" prop="workorderName">
          <el-input v-model="form.workorderName" disabled placeholder="选择工单后自动填充" />
        </el-form-item>
        <el-form-item label="操作人" prop="operator">
          <el-input v-model="form.operator" placeholder="请输入操作人" />
        </el-form-item>
        <el-form-item label="是否正常停机" style="width: 320px;" prop="isNormally">
          <el-switch v-model="form.isNormally" active-value="1" inactive-value="0">
          </el-switch>
          <!-- <el-input v-model="form.isNormally" placeholder="请输入是否正常停机" /> -->
        </el-form-item>
        <el-row>
          <el-form-item label="停机原因">
            <el-input v-model="form.shutdownContent" type="textarea" placeholder="请输入内容" />
            <!-- <editor v-model="form.shutdownContent" :min-height="192"/> -->
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-row>


        <!-- <el-form-item label="数据行状态(0:正常/1:删除)" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入数据行状态(0:正常/1:删除)" />
        </el-form-item>
        <el-form-item label="预留字段1" prop="attr1">
          <el-input v-model="form.attr1" placeholder="请输入预留字段1" />
        </el-form-item>
        <el-form-item label="预留字段2" prop="attr2">
          <el-input v-model="form.attr2" placeholder="请输入预留字段2" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listShutdown,
    getShutdown,
    delShutdown,
    addShutdown,
    updateShutdown
  } from "@/api/mes/dv/shutdown";
  import MachinerySelectSingle from "@/components/machinerySelect/single.vue";
  import WorkorderSelect from "@/components/workorderSelect/single.vue"

  export default {
    name: "Shutdown",
    components: {
      MachinerySelectSingle,
      WorkorderSelect
    },
    dicts: ['mes_shutdown_type'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 设备停复机记录表格数据
        shutdownList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          recordCode: null,
          shutdownType: null,
          machineryId: null,
          machineryCode: null,
          machineryName: null,
          shutdownContent: null,
          isNormally: null,
          shutdownTime: null,
          resumptionTime: null,
          affectDuration: null,
          workorderId: null,
          workorderCode: null,
          workorderName: null,
          operator: null,
          attr1: null,
          attr2: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          recordCode: [{
            required: true,
            message: "停机记录编号不能为空",
            trigger: "blur"
          }],
          shutdownType: [{
            required: true,
            message: "停机类型不能为空",
            trigger: "blur"
          }],
          machineryCode: [{
            required: true,
            message: "设备编号不能为空",
            trigger: "blur"
          }],
          machineryName: [{
            required: true,
            message: "设备名称不能为空",
            trigger: "blur"
          }],
          shutdownContent: [{
            required: true,
            message: "停机原因不能为空",
            trigger: "blur"
          }],
          shutdownTime: [{
            required: true,
            message: "停机时间不能为空",
            trigger: "blur"
          }],
          affectDuration: [{
            required: true,
            message: "影响时长不能为空",
            trigger: "blur"
          }],
          workorderId: [{
            required: true,
            message: "工单ID不能为空",
            trigger: "blur"
          }],
          workorderCode: [{
            required: true,
            message: "任务编号不能为空",
            trigger: "blur",
          }],
          workorderName: [{
            required: true,
            message: "任务名称不能为空",
            trigger: "blur",
          }],
          operator: [{
            required: true,
            message: "操作人不能为空",
            trigger: "blur"
          }],
          delFlag: [{
            required: true,
            message: "数据行状态(0:正常/1:删除)不能为空",
            trigger: "blur"
          }],
        }
      };
    },
    created() {
      this.getList();
    },
    watch: {
      'queryParams.shutdownTime': {
        handler(newData, oldData) {
          if (newData != null && newData.length > 1) {
            this.queryParams.shutdownTimeStart = newData[0];
            this.queryParams.shutdownTimeEnd = newData[1];
          }
        }
      },
      'queryParams.resumptionTime'(newData, oldData) {
        if (newData != null && newData.length > 1) {
          this.queryParams.resumptionTimeStart = newData[0];
          this.queryParams.resumptionTimeEnd = newData[1];
        }
      }
    },
    methods: {
      /** 查询设备停复机记录列表 */
      getList() {
        this.loading = true;
        listShutdown(this.queryParams).then(response => {
          this.shutdownList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      //计算复机时间
      calculateEndTime(){
        if(this.form.shutdownTime !=null && this.form.affectDuration !=null){
            this.form.affectDuration = parseFloat(this.form.affectDuration);
            let parts = this.form.shutdownTime.split(' ');
            let startDate = new Date(parts[0]);
            startDate = startDate.getFullYear() + '-'
                + (startDate.getMonth()+1) + '-'
                + startDate.getDate() + ' '
                    + parts[1].split(':')[0] + ':'
                    + '00' + ':'
                    + '00';
            this.form.shutdownTime = startDate;
            startDate = Date.parse(new Date(startDate))/1000;
            startDate += 60 * this.form.affectDuration; //这里以12小时为一个单位
            let endDate = new Date(parseInt(startDate) * 1000);
            this.form.resumptionTime = endDate.getFullYear() + '-'
                          + (endDate.getMonth()+1) + '-'
                          + endDate.getDate() + ' '
                            + endDate.getHours() + ':'
                            + endDate.getMinutes() + ':'
                            + endDate.getSeconds();
        }
      },
      // 生产工单选择弹出
      handleWorkorderSelect() {
        this.$refs.woSelect.showFlag = true;
      },
      // 生产工单选择回调
      onWorkorderSelected(row) {
        if (row != undefined && row != null) {
          this.form.workorderId = row.workorderId;
          this.form.workorderCode = row.workorderCode;
          this.form.workorderName = row.workorderName;
        }
      },
      //设备资源选择弹出
      handleMachineryAdd() {
        this.$refs.machinerySelect.showFlag = true;
      },
      //设备资源选择回调
      onMachineryAdd(row) {
        if (row != undefined && row != null) {
          this.form.machineryId = row.machineryId;
          this.form.machineryCode = row.machineryCode;
          this.form.machineryName = row.machineryName;
        }
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          recordId: null,
          recordCode: null,
          shutdownType: null,
          machineryId: null,
          machineryCode: null,
          machineryName: null,
          shutdownContent: null,
          isNormally: null,
          shutdownTime: null,
          resumptionTime: null,
          affectDuration: null,
          workorderId: null,
          workorderCode: null,
          workorderName: null,
          operator: null,
          remark: null,
          delFlag: null,
          attr1: null,
          attr2: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.recordId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加设备停复机记录";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const recordId = row.recordId || this.ids
        getShutdown(recordId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改设备停复机记录";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.recordId != null) {
              updateShutdown(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addShutdown(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const recordIds = row.recordId || this.ids;
        this.$modal.confirm('是否确认删除设备停复机记录编号为"' + recordIds + '"的数据项？').then(function() {
          return delShutdown(recordIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('mes/dv/shutdown/export', {
          ...this.queryParams
        }, `shutdown_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
<style scoped>
  .el-select,
  .el-date-editor {
    width: 200px;
  }

  .el-date-editor.el-input {
    width: 200px;
  }
</style>
